var options = require('../general/qiniu/config.js').options;
var store = require('../general/qiniu/store.js');
var moment = require('moment');
var randomstring = require("randomstring");
var fs = require('fs');
var formidable = require("formidable");
var cacheFolder = './public/uploads/images';
var returnFolder = "/uploads/images";

exports.upload = async function(req, res) {

    var userDirPath = cacheFolder;
    var UPLOAD_FOLDER = cacheFolder;
    if (!fs.existsSync(userDirPath)) {
        fs.mkdirSync(userDirPath);
    }
    var form = new formidable.IncomingForm(); //创建上传表单
    form.encoding = 'utf-8'; //设置编辑
    form.uploadDir = userDirPath; //设置上传目录
    form.keepExtensions = true; //保留后缀
    form.maxFieldsSize = 2 * 1024 * 1024; //文件大小
    form.type = true;
    var displayUrl;
    form.parse(req, function(err, fields, files) {
        if (err) {
            res.send(err);
            return;
        }
        var extName = ''; //后缀名
        switch (files.upload.type) {
            case 'image/pjpeg':
                extName = 'jpg';
                break;
            case 'image/jpeg':
                extName = 'jpg';
                break;
            case 'image/png':
                extName = 'png';
                break;
            case 'image/x-png':
                extName = 'png';
                break;
        }
        if (extName.length === 0) {
            res.send({
                code: 202,
                msg: '只支持png和jpg格式图片'
            });
            return;
        } else {
            var avatarName = '/' + Date.now() + '.' + extName;
            var newPath = form.uploadDir + avatarName;
            displayUrl = returnFolder +  avatarName;
            
            fs.rename(files.upload.path, newPath); //重命名
            res.send({
                code: 200,
                msg: displayUrl
            });
        }
    });
};
exports.info = function(req, res, next) {
	res.send({
		version: options.version
	});

	return next();
};
exports.getqiniu= function(req, res, next) {
    //console.log(options.ueditorConfig);
	var params = req.query;

	var action = params['action'];

	if (action == 'config') {
		res.send(options.ueditorConfig);
	} else if (action == 'listimage' || action == 'listfile') {
		var start = parseInt(params['start'] || 0);
		var size = parseInt(params['size'] || 10);

		var storeParams = {
			prefix: action == 'listimage' ? 'image/' : 'file/',
			start: start,
			limit: size
		}

		store.listQiniu(storeParams, function(err, ret) {
			res.send(ret);
			return next();
		})

	} else {
		res.send();
	}

	//return next();
};
exports.postqiniu=function(req, res, next) {
	var params = req.query;

	var action = params['action'];
	var key = '/' + moment().format('YYYYMMDD') + '/' + (+new Date()) + randomstring.generate(6);
	switch (action) {
		case 'uploadvideo':
			key = 'video' + key;
			break;
		case 'uploadfile':
			key = 'file' + key;
			break;
		default:
			key = 'image' + key;
			break;
	}

	if (action == 'uploadimage' || action == 'uploadvideo' || action == 'uploadfile') {
        var form = new formidable.IncomingForm();
        form.parse(req, function(err, fields, files) {
            var file = files['upfile'];
            
            if (!file) {
                res.send();
                return next();
            }

            if (action == 'uploadfile') {
                key += '/' + file.name;
            }

            var storeParams = {
                key: key,
                filePath: file.path,
                fileName: file.name
            }

            store.fileToQiniu(storeParams, function(err, ret) {
                res.send(ret);
                return next();
            })
        });
	} else if (action == 'uploadscrawl') {
		var data = req.params['upfile'];
		if (!data) {
			res.send();
			return next();
		}

		var storeParams = {
			key: key,
			data: new Buffer(data, 'base64')
		}

		store.dataToQiniu(storeParams, function(err, ret) {
			res.send(ret);
			return next();
		})
	}
};